import random
import sys

import pygame


pygame.init()

# -------------  data  ---------------------

FPS = 60
WIDTH = 600
HEIGHT = 600

# 0 没有棋子； 1 表示 X； 2 表示 O
board_data = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
]

turn = 0
is_game_over = False
winner = 0

# -------------  RESOURCES  ---------------------
img_X = pygame.image.load('img/X.png')
img_O = pygame.image.load('img/O.png')

large_font = pygame.font.SysFont(None, 160, False)
middle_font = pygame.font.SysFont(None, 40, False)

x_win_msg = large_font.render(" X win! ", True, "white", "blue")
o_win_msg = large_font.render(" O win! ", True, "white", "blue")
win_msg_rect = x_win_msg.get_rect(center=(300, 300))
win_msg_rect.y -= 100

restart_msg = middle_font.render(" press key 'R' to restart ", True, "white", "blue")
restart_msg_rect = restart_msg.get_rect(center=(300, 300))
restart_msg_rect.y += 50

# -------------  INIT  ---------------------

pygame.display.set_caption("TicTacToe Base")

clock = pygame.time.Clock()

screen = pygame.display.set_mode((WIDTH, HEIGHT))

# -------------  FUNCTIONS  ---------------------
def draw_lines():
    pygame.draw.line(screen, "darkgreen", (0, 200), (600, 200), 5)
    pygame.draw.line(screen, "darkgreen", (0, 400), (600, 400), 5)
    pygame.draw.line(screen, "darkgreen", (200, 0), (200, 600), 5)
    pygame.draw.line(screen, "darkgreen", (400, 0), (400, 600), 5)

def drawX(row, col):
    screen.blit(img_X, (col * 200, row * 200))

def drawO(row ,col):
    screen.blit(img_O, (col * 200, row * 200))

def draw_board():
    for row_index, row in enumerate(board_data):
        for col_index, cell in enumerate(row):
            # print(f'[{row_index},{col_index}]: {cell}')
            if board_data[row_index][col_index] == 1:
                drawX(row_index, col_index)
            elif board_data[row_index][col_index] == 2:
                drawO(row_index, col_index)

def check_win():
    for row in range(3):
        if board_data[row][0] == board_data[row][1] \
                and board_data[row][1] == board_data[row][2] \
                and board_data[row][0] != 0:
            # if board_data[row][0] == 1:
            #     print("X win")
            # elif board_data[row][0] == 2:
            #     print("O win")
            return board_data[row][0]


    for col in range(3):
        if board_data[0][col] == board_data[1][col] \
                and board_data[1][col] == board_data[2][col] \
                and board_data[0][col] != 0:
            # if board_data[0][col] == 1:
            #     print("X win")
            # elif board_data[0][col] == 2:
            #     print("O win")
            return board_data[0][col]

    if board_data[0][0] == board_data[1][1] \
            and board_data[1][1] == board_data[2][2] \
            and board_data[1][1] != 0:
        # if board_data[1][1] == 1:
        #     print("X win")
        # elif board_data[1][1] == 2:
        #     print("O win")
        return board_data[1][1]

    if board_data[0][2] == board_data[1][1] \
            and board_data[1][1] == board_data[2][0] \
            and board_data[1][1] != 0:
        # if board_data[1][1] == 1:
        #     print("X win")
        # elif board_data[1][1] == 2:
        #     print("O win")
        return board_data[1][1]

    return 0


def game_over(win_player):
    global is_game_over
    global winner

    winner = win_player
    is_game_over = True
    # print("Game Over", win_player)

def restart_game():
    global is_game_over
    global board_data
    global turn
    global winner

    winner = 0
    is_game_over= False
    turn = 0
    board_data = [
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]
    ]


def random_ai():
    result = []
    # 找到空格，放到列表中
    for row in range(3):
        for col in range(3):
            if board_data[row][col] == 0:
                result.insert(-1, (row, col))
    # 随机选取空格，并返回
    row, col = random.choice(result)
    print(row,col)
    return row, col

# -------------  MAIN LOOP  ---------------------
isRunning = True
while isRunning:
    # event
    events = pygame.event.get()
    for e in events:
        if e.type == pygame.QUIT:
            isRunning = False
        if e.type == pygame.MOUSEBUTTONDOWN:
            if not is_game_over:
                mx, my = e.pos
                col = mx // 200
                row = my // 200
                # 判断是否可以落子
                if board_data[row][col] == 0:
                    turn += 1
                    if turn % 2 == 1:   # X 回合
                        board_data[row][col] = 1

                        win = check_win()
                        if win != 0:
                            game_over(win)
                        else:
                            #  现在，我们加入一个傻乎乎的 AI， 他只是从空余的格子中随机选取一个落子
                            row, col = random_ai()
                            board_data[row][col] = 2
                            turn += 1

                            win = check_win()
                            if win != 0:
                                game_over(win)
                            

                    # else:   # O 回合
                    #     board_data[row][col] = 2
                    # # print(f'turn: {turn}' )
                    # # print(board_data)
                    #
                    # win = check_win()
                    # if win != 0:
                    #     game_over(win)
        if e.type == pygame.KEYDOWN:
            if is_game_over:
                # print(e)
                if e.key == pygame.K_r:
                    restart_game()


    # update

    # draw
    screen.fill("yellowgreen")

    draw_board()
    draw_lines()

    if is_game_over:
        if winner == 1:
            screen.blit(x_win_msg, win_msg_rect)
        elif winner == 2:
            screen.blit(o_win_msg, win_msg_rect)

        screen.blit(restart_msg, restart_msg_rect)

    pygame.display.flip()

    # clock

pygame.quit()
sys.exit()
